package Comp355Final.main;

import java.util.Locale;

import com.google.tts.TextToSpeechBeta;
import com.google.tts.TextToSpeechBeta.OnInitListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * The GUI for text reader
 * @author chung
 *
 */
public class GUIReadText extends Activity implements OnInitListener{
	private static TextView txtview;
	private Config myconfig;
	private ScrollView scllview;
	private FileIO fileio;
	private String chapter_name;
	private String book_folder;
	private BookMark mybookmark;
	private static String defaultfontcolor,defaultfontsize;
	private static boolean manualfontcolor=false,manualfontsize=false;
	private String dest;
	private String charset;
	//private static 
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	Bundle extras = getIntent().getExtras();
    	dest = extras.getString("dest");
    	charset = extras.getString("charset");
    	chapter_name = extras.getString("book_name");
    	book_folder = extras.getString("book_folder");
    	
    	myconfig = new Config(this);
    	if(!manualfontcolor)
    	defaultfontcolor=myconfig.getActualfontColor();
    	if(!manualfontsize)
    	defaultfontsize=myconfig.getActualfontSize();
    	
    	scllview = new ScrollView(this);
    	ScrollView.LayoutParams scllview_param = new ScrollView.LayoutParams(
        		ViewGroup.LayoutParams.FILL_PARENT,
        		ViewGroup.LayoutParams.FILL_PARENT);
        scllview.setBackgroundColor(Color.WHITE);
        scllview.setBackgroundDrawable(myconfig.return_bg());
    	LinearLayout Llay = new LinearLayout(this);
        LinearLayout.LayoutParams Llay_param = new LinearLayout.LayoutParams(
        		ViewGroup.LayoutParams.FILL_PARENT,
        		ViewGroup.LayoutParams.FILL_PARENT);
    	Llay.setOrientation(LinearLayout.VERTICAL);
    	
    	fileio = new FileIO();

    	String hole_passage = fileio.textViewReadfileOP(dest, charset);
    	txtview = new TextView(this);
    	txtview.setText(hole_passage);
    	txtview.setTextColor(Utility.return_actualColor(defaultfontcolor));
    	txtview.setTextSize(TypedValue.COMPLEX_UNIT_SP,Float.valueOf(defaultfontsize));
    	//txtview.bringPointIntoView(offset)
    	Llay.addView(txtview);
    	
    	mybookmark = new BookMark(this.fileio,this.scllview,chapter_name,book_folder);
    	HaveBookMark = mybookmark.GetTheBookMark();
    	if(HaveBookMark)
    	{
    		Utility.getAlertDialog("Last Bookmark found", "Do you want to load back the bookmark?", this, new DiologClickListener(this,mybookmark)).show();
    		//Utility.quick_dialog("Moving the scroll", this);
    		
    	}
    	init_theVoice();
    	//scllview.
        this.setTitle("Text reader - "+chapter_name);
        scllview.addView(Llay, Llay_param);
        this.setContentView(scllview, scllview_param);
    }
    private boolean HaveBookMark;
    private String[] All_color;
    private float[] All_txtsize;
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
	   menu.add(0, 0, 0, "Return BookShelf").setIcon(android.R.drawable.ic_menu_revert);
	   SubMenu TxtSize =menu.addSubMenu(0, 1, 1, "Font Size").setIcon(android.R.drawable.ic_menu_zoom);
	   //ic_menu_zoom
	   //txtview.setTextColor(color);
	   SubMenu color = menu.addSubMenu(0, 2, 2, "Font Color").setIcon(android.R.drawable.ic_menu_edit);

	
	   All_color = Utility.returnAllColor();
	   
	   for(int i=0;i< All_color.length;i++)
	   {
		   color.add(0,5+i,0,All_color[i]);
	   }
	   All_txtsize = Utility.returnAllTxtSize();
	   
	   for(int i=0;i< All_txtsize.length;i++)
	   {
		   TxtSize.add(0,5+All_color.length+i,0,String.valueOf(All_txtsize[i]).substring(0, 2)+"px");
	   }
	   menu.add(0, 3, 3, "BookMark").setIcon(android.R.drawable.ic_menu_save);
	   SubMenu more_functions = menu.addSubMenu(0, 4, 4, "More").setIcon(android.R.drawable.ic_menu_more);
	   more_functions.setHeaderTitle("More functions");
	   more_functions.add(0, 5+All_color.length+All_txtsize.length+1,0,"Go to");
	  
	   SubMenu listen_toMenu = menu.addSubMenu(0, 5+All_color.length+All_txtsize.length,0,"Play It").setIcon(android.R.drawable.ic_menu_upload_you_tube);
	   listen_toMenu.setHeaderTitle("Select language");
	   listen_toMenu.add(0, 5+All_color.length+All_txtsize.length+2,0,"ENGLISH");
	   listen_toMenu.add(0, 5+All_color.length+All_txtsize.length+3,0,"SIMPLIFIED_CHINESE");
	   listen_toMenu.add(0, 5+All_color.length+All_txtsize.length+4,0,"TRADITIONAL_CHINESE");
	   listen_toMenu.add(0, 5+All_color.length+All_txtsize.length+5,0,"FRENCH");
	   listen_toMenu.add(0, 5+All_color.length+All_txtsize.length+6,0,"GERMAN");
	   listen_toMenu.add(0, 5+All_color.length+All_txtsize.length+7,0,"JAPANESE");
	   listen_toMenu.add(0, 5+All_color.length+All_txtsize.length+8,0,"ITALIAN");
	   listen_toMenu.add(0, 5+All_color.length+All_txtsize.length+9,0,"KOREAN");
	    
	    
	    

	   return super.onCreateOptionsMenu(menu); 
   }
	private String locale_to_listen;
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	if(item.getItemId() >= 5 && item.getItemId()<(5+All_color.length))
    	{
    		defaultfontcolor=All_color[item.getItemId()-5];
    		manualfontcolor=true;
    		txtview.setTextColor(Utility.return_actualColor(All_color[item.getItemId()-5]));
    	}
    	else if(item.getItemId()>=5+All_color.length && item.getItemId()<(5+All_color.length+All_txtsize.length))
    	{
    		defaultfontsize=String.valueOf(All_txtsize[item.getItemId()-5-All_color.length]);
    		manualfontsize=true;
    		Utility.quick_dialog("Text size changed to "+String.valueOf(All_txtsize[item.getItemId()-5-All_color.length]).substring(0,2)+"px", this);
    		txtview.setTextSize(TypedValue.COMPLEX_UNIT_SP,All_txtsize[item.getItemId()-5-All_color.length]);
    	} 
    	else if(item.getItemId() ==5+All_color.length+All_txtsize.length)
    	{
    	//	speak_theVoice(txtview.getText().toString());
    	//	Utility.quick_dialog("Listen to the passage clicked", this);
    	}
    	else if(item.getItemId() ==5+All_color.length+All_txtsize.length+1)
    	{
    		//Utility.quick_dialog("Go to clicked", this);
    		isShowingDialog=true;
    		org_y_pos=scllview.getScrollY();
    		scllview.post(new Runnable() {
				public void run()
				{
					scllview.fullScroll(ScrollView.FOCUS_DOWN);
					
				}
				});
    		this.showDialog(DIALOG_RENAME_ENTRY);

    	}
    	else if(item.getItemId() ==5+All_color.length+All_txtsize.length+2)
    	{
    		locale_to_listen="ENGLISH";
    		speak_theVoice(txtview.getText().toString());
    	}
    	else if(item.getItemId() ==5+All_color.length+All_txtsize.length+3)
    	{
    		locale_to_listen="SIMPLIFIED_CHINESE";
    		speak_theVoice(txtview.getText().toString());
    	}
    	else if(item.getItemId() ==5+All_color.length+All_txtsize.length+4)
    	{
    		locale_to_listen="TRADITIONAL_CHINESE";
    		speak_theVoice(txtview.getText().toString());
    	}
		else if(item.getItemId() ==5+All_color.length+All_txtsize.length+5)
		{
			locale_to_listen="FRENCH";
			speak_theVoice(txtview.getText().toString());
		}
		else if(item.getItemId() ==5+All_color.length+All_txtsize.length+6)
		{
			locale_to_listen="GERMAN";
			speak_theVoice(txtview.getText().toString());
		}
		else if(item.getItemId() ==5+All_color.length+All_txtsize.length+7)
		{
			locale_to_listen="JAPANESE";
			speak_theVoice(txtview.getText().toString());
		}
		else if(item.getItemId() ==5+All_color.length+All_txtsize.length+8)
		{
			locale_to_listen="ITALIAN";
			speak_theVoice(txtview.getText().toString());
		}
		else if(item.getItemId() ==5+All_color.length+All_txtsize.length+9)
		{
			locale_to_listen="KOREAN";
			speak_theVoice(txtview.getText().toString());
		}
    	else
    	{
	    	//txtview.setTextSize(TypedValue.COMPLEX_UNIT_SP,(float)20);
	    	switch(item.getItemId())
	    	{
		    	case 0: 
					Intent int_ent = new Intent(this, GUIBookShelfBkSelect.class);
					this.startActivity(int_ent);
					this.finish();
		    		break;
		    	case 1:
		
		    		break;
		    	case 2:
		    		break;
		    	case 3:
		    		/*
		    		int scll_x = scllview.getScrollX();
		    		int scll_y = scllview.getScrollY();
		    		Utility.quick_dialog(" " +scll_x+" "+scll_y, this);
		    		scllview.scrollTo(scll_x, scll_y);
		    		*/
		    		
		    		mybookmark.SetTheBookMark();
		    		Utility.quick_dialog("Bookmark saved", this);
		    		break;
		    	case 4:
		    		
		    		break;
	    	}
    	}
    	return super.onOptionsItemSelected(item);
    }
    boolean isShowingDialog = false;
    @Override
    public void onDestroy()
    {
    
    	manualfontcolor=false;
    	manualfontsize=false;
		if(mTTS!=null){
			mTTS.shutdown();
		}
    	super.onDestroy();
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	
    	manualfontcolor=true;
    	manualfontsize=true;
    	super.onConfigurationChanged(newConfig);
    }
   // DialogInterface.OnDismissListener
    private static final int DIALOG_RENAME_ENTRY = 8;
    @Override   
    protected Dialog onCreateDialog(int id) {
    	switch(id){
        case DIALOG_RENAME_ENTRY:
        	// This example shows how to add a custom layout to an AlertDialog
        	final SeekBar myseekbar = new SeekBar(this);
        	final View textEntryView2 = myseekbar;
        	return new AlertDialog.Builder(GUIReadText.this)
        	//.setIconAttribute(android.R.drawable.)
        	.setTitle("Go To")
        	.setView(textEntryView2)
        	.setPositiveButton("ok", new DialogInterface.OnClickListener() {
        		public void onClick(DialogInterface dialog, int whichButton) {
        		//	Utility.quick_dialog("OK clicked", GUIReadText.this);
        			isShowingDialog=false;
        			int seek_bar_progress = myseekbar.getProgress();
        			int seek_bar_max = myseekbar.getMax();
        			float proportion = (float)seek_bar_progress/(float)seek_bar_max;
        			
        			//Utility.quick_dialog(String.valueOf(proportion), GUIReadText.this);
        			full_y_pos = scllview.getScrollY();
        			MoveTheScrollViewByPortion(proportion);
        			} 
        		})
        		.setOnCancelListener(new DialogInterface.OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
					//	Utility.quick_dialog("cancel clicked", GUIReadText.this);
						// TODO Auto-generated method stub
						isShowingDialog=false;
        				/* User clicked cancel so do some stuff */
        				scllview.post(new Runnable() {
        					public void run()
        					{
        						scllview.scrollTo(scllview.getScrollX(), org_y_pos);
        					}
        					});
					}
				})
        		.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
        			public void onClick(DialogInterface dialog, int whichButton) {
        			//	Utility.quick_dialog("cancel button clicked", GUIReadText.this);
        				isShowingDialog=false;
        				/* User clicked cancel so do some stuff */
        				scllview.post(new Runnable() {
        					public void run()
        					{
        						scllview.scrollTo(scllview.getScrollX(), org_y_pos);
        					}
        					});
        				//
        				} 
        			})
        			.create();	

    	}
    	return null;
    	}
   
 	
    private int full_y_pos;
    private int tmp_y_pos;
    private int org_y_pos;
	public void MoveTheScrollViewByPortion(final float proportion)
	{
		
		tmp_y_pos= (int)(full_y_pos*proportion);//*proportion
  		scllview.post(new Runnable() {
			public void run()
			{
				scllview.scrollTo(scllview.getScrollX(), tmp_y_pos);
			}
			});
	//	Utility.quick_dialog(String.valueOf(tmp_y_pos), GUIReadText.this);
		//Utility.quick_dialog(String.valueOf(tmp_y_pos), this);
		//System.out.println("x-pos:"+x_pos+"y-pos"+y_pos);
		//scllview.scrollBy(x_pos, y_pos);
		

	}
	private TextToSpeechBeta mTTS;
	private boolean notFirst_timeToInit=false;
	private static final String TAG = "TTS Demo";  
	private static final int REQ_TTS_STATUS_CHECK = 0;  
	private int status,version;
	@Override
	public void onInit(int status, int version) {
		this.status=status;
		this.version=version;
	}
	private void init_theVoice(){
        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeechBeta.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, REQ_TTS_STATUS_CHECK);
       
	}
	private void refresh_me()
	{
		Intent newIntent = new Intent(this, GUIReadText.class);
		newIntent.putExtra("book_name",chapter_name);
		newIntent.putExtra("book_folder",book_folder);
		newIntent.putExtra("dest",dest);
		newIntent.putExtra("charset", charset);
		this.startActivity(newIntent);
		this.finish();

    	
	}
	private void speak_theVoice(String ttsText){
		if(notFirst_timeToInit && version == -1)
		{
			refresh_me();
			//Utility.quick_dialog("Please reboot your program after installation.", this);
		}
		if(!notFirst_timeToInit)
		{
			// TODO Auto-generated method stub
			Log.v(TAG, "version = " + String.valueOf(version));
			if(version == -1)
			{
				alertInstallEyesFreeTTSData();
			}
			else
			{
				if(status == TextToSpeechBeta.SUCCESS)
				{
					Log.v(TAG, "success to init tts");
					mTTS.setEngineByPackageNameExtended("com.google.tts");
		    		
					int result = mTTS.setLanguage(Locale.getDefault());
					if(this.locale_to_listen.equals("ENGLISH"))
					{
						result = mTTS.setLanguage(Locale.ENGLISH);
					}
					else if(this.locale_to_listen.equals("SIMPLIFIED_CHINESE"))
					{
						result = mTTS.setLanguage(Locale.SIMPLIFIED_CHINESE);
					}
					else if(this.locale_to_listen.equals("TRADITIONAL_CHINESE"))
					{
						result = mTTS.setLanguage(Locale.TRADITIONAL_CHINESE);
					}
					else if(this.locale_to_listen.equals("FRENCH"))
					{
						result = mTTS.setLanguage(Locale.FRENCH);
					}
					else if(this.locale_to_listen.equals("GERMAN"))
					{
						result = mTTS.setLanguage(Locale.GERMAN);
					}
					else if(this.locale_to_listen.equals("JAPANESE"))
					{
						result = mTTS.setLanguage(Locale.JAPANESE);
					}
					else if(this.locale_to_listen.equals("ITALIAN"))
					{
						result = mTTS.setLanguage(Locale.ITALIAN);
					}
					else if(this.locale_to_listen.equals("KOREAN"))
					{
						result = mTTS.setLanguage(Locale.KOREAN);
					}
					
					if(result == TextToSpeechBeta.LANG_MISSING_DATA || result == TextToSpeechBeta.LANG_NOT_SUPPORTED)
				
					{
						Utility.quick_dialog("Language is not available",this);
						Log.v(TAG, "Language is not available");
					}
					else
					{
						//mTTS.speak("Nice to meet you, my friend!", TextToSpeechBeta.QUEUE_ADD, null);
					}
				}
				else
				{
					Log.v(TAG, "failed to init tts");
				}
			}
			notFirst_timeToInit=true;
		}
	//	 mTTS.speak(ttsText, TextToSpeechBeta.QUEUE_ADD, null);
		voiceThread voicethread = new voiceThread(this,ttsText,mTTS);
		voicethread.start();
	}
	protected  void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == REQ_TTS_STATUS_CHECK)
		{
			switch (resultCode) {
			case TextToSpeechBeta.Engine.CHECK_VOICE_DATA_PASS:
			
			{
			
		        mTTS = new TextToSpeechBeta(this, this);
		        Log.v(TAG, "TTS Engine is installed!");  
				
			}
				
				break;
			case TextToSpeechBeta.Engine.CHECK_VOICE_DATA_BAD_DATA:
			
			case TextToSpeechBeta.Engine.CHECK_VOICE_DATA_MISSING_DATA:
			
			case TextToSpeechBeta.Engine.CHECK_VOICE_DATA_MISSING_VOLUME:
				
			{
				
				Log.v(TAG, "Need language stuff:"+resultCode);
				Intent dataIntent = new Intent();
				dataIntent.setAction(TextToSpeechBeta.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(dataIntent);
			}
				break;
			case TextToSpeechBeta.Engine.CHECK_VOICE_DATA_FAIL:
				
			default:
				Log.v(TAG, "Got a failure. TTS apparently not available");
				break;
			}
		}
		else
		{
			
		}
	}
	

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if(mTTS != null)
		{
			mTTS.stop();
		}
	}
	
	
	private void alertInstallEyesFreeTTSData()
	{
		Builder alertInstall = new AlertDialog.Builder(this)
			.setTitle("Missing important sounding data")
			.setMessage("Download the important sounding data")
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
			
					String ttsDataUrl = "http://eyes-free.googlecode.com/files/tts_3.1_market.apk";
					Uri ttsDataUri = Uri.parse(ttsDataUrl);
					Intent ttsIntent = new Intent(Intent.ACTION_VIEW, ttsDataUri);
					startActivity(ttsIntent);
					notFirst_timeToInit=true;
				}
			})
			.setOnCancelListener(new DialogInterface.OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
					notFirst_timeToInit=false;
					// TODO Auto-generated method stub
					
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					notFirst_timeToInit=false;
					// TODO Auto-generated method stub
					//finish();
					
				}
			});
			alertInstall.create().show();
		
	}
	public String get_the_currentChar()
	{
		return this.charset;
	}
}
